package com.agileboot.domain.system.user.db;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.system.UserInfo;
import com.agileboot.common.core.dto.ResponseDTO;
import com.agileboot.common.core.page.AbstractPageQuery;
import com.agileboot.domain.system.post.db.SysPostEntity;
import com.agileboot.domain.system.role.db.SysRoleEntity;
import com.agileboot.domain.system.user.dto.UserDTO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.List;
import java.util.Optional;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author valarchie
 * @since 2022-06-16
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUserEntity> implements SysUserService {

    @Value("${spring.mail.username:2183517383@qq.com}")
    private String username;
//    @Autowired
//    private  MailSender mailSender;


    @Override
    public boolean isUserNameDuplicated(String username) {
        QueryWrapper<SysUserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        return this.baseMapper.exists(queryWrapper);
    }


    @Override
    public boolean isPhoneDuplicated(String phone, Long userId) {
        QueryWrapper<SysUserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne(userId != null, "user_id", userId)
                .eq("phone_number", phone);
        return baseMapper.exists(queryWrapper);
    }


    @Override
    public boolean isEmailDuplicated(String email, Long userId) {
        QueryWrapper<SysUserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne(userId != null, "user_id", userId)
                .eq("email", email);
        return baseMapper.exists(queryWrapper);
    }


    @Override
    public SysRoleEntity getRoleOfUser(Long userId) {
        List<SysRoleEntity> list = baseMapper.getRolesByUserId(userId);
        return list.isEmpty() ? null : list.get(0);
    }


    @Override
    public SysPostEntity getPostOfUser(Long userId) {
        List<SysPostEntity> list = baseMapper.getPostsByUserId(userId);
        return list.isEmpty() ? null : list.get(0);
    }


    @Override
    public Set<String> getMenuPermissionsForUser(Long userId) {
        return baseMapper.getMenuPermsByUserId(userId);
    }


    @Override
    public SysUserEntity getUserByUserName(String userName) {
        QueryWrapper<SysUserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", userName);
        return this.getOne(queryWrapper);
    }


    @Override
    public Page<SysUserEntity> getUserListByRole(AbstractPageQuery<SysUserEntity> query) {
        return baseMapper.getUserListByRole(query.toPage(), query.toQueryWrapper());
    }


    @Override
    public Page<SearchUserDO> getUserList(AbstractPageQuery<SearchUserDO> query) {
        return baseMapper.getUserList(query.toPage(), query.toQueryWrapper());
    }

    @Override
    public SysUserEntity findUserByNameOrEmail(String email) {
        return baseMapper.findUserByNameOrEmail(email);
    }

//    @Override
//    public ResponseDTO sendValidateEmail(String email) {
//        String key = "email:" + email;
//        if (Boolean.TRUE.equals(redisTemplate.hasKey(key))) {
//            Long expire = Optional.ofNullable(redisTemplate.getExpire(key, TimeUnit.SECONDS)).orElse(0L);
//            if (expire > 120) return ResponseDTO.fail("请求频繁，请稍后再试~");
//        }
//        if (baseMapper.findUserByNameOrEmail(email) != null) {
//            return ResponseDTO.fail("邮箱已被注册~~");
//        }
//        Random random = new Random();
//        int code = random.nextInt(899999) + 100000;
//        SimpleMailMessage message = new SimpleMailMessage();
//
//        System.out.println(username + "\t" + email + "\t" + code);
//
//        message.setFrom(username);
//        message.setTo(email);
//        message.setSubject("你的验证邮件");
//        message.setText("验证码是" + code);
//        try {
//            mailSender.send(message);
//            redisTemplate.opsForValue().set(key, String.valueOf(code), 3, TimeUnit.MINUTES);
//            return ResponseDTO.ok("发送成功，请注意接收");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return ResponseDTO.fail("发送失败，请联系管理员");
//    }

//    @Override
//    public ResponseDTO validateAndRegister(UserDTO userDTO) {
//        String key = "email:" + userDTO.getEmail();
//        if (Boolean.TRUE.equals(redisTemplate.hasKey(key))) {
//            String code = redisTemplate.opsForValue().get(key);
//            if (code == null) return ResponseDTO.fail("验证码已失效，请重新获取");
//            if (code.equals(userDTO.getCode())) {
//                SysUserEntity user = baseMapper.findUserByNameOrEmail(userDTO.getUsername());
//                if (user != null) return ResponseDTO.fail("用户名已存在");
//                redisTemplate.delete(key);
//                SysUserEntity sysUserEntity = new SysUserEntity();
//                BeanUtil.copyProperties(userDTO, sysUserEntity);
//                if (baseMapper.insert(sysUserEntity)>0) {
//                    return ResponseDTO.ok("注册成功");
//                } else {
//                    return ResponseDTO.fail("内部错误，请联系管理员");
//                }
//            } else {
//                return ResponseDTO.fail("验证码错误，请检查后提交");
//            }
//        }
//        return ResponseDTO.fail("请先获取验证码");
//    }

}
